Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
The cron npm package is used for scheduling tasks to be executed at specific times or intervals. It is inspired by the Unix cron scheduler and allows for the use of cron syntax to schedule tasks in a Node.js environment. This package is useful for setting up jobs like backups, sending emails, or cleaning up databases at regular intervals.
Basic Cron Job
This feature allows you to create a basic cron job that runs at a specified interval. In the provided code sample, a new CronJob is created that logs a message to the console every second.
"const CronJob = require('cron').CronJob;\nconst job = new CronJob('* * * * * *', function() {\n console.log('You will see this message every second');\n}, null, true, 'America/Los_Angeles');\njob.start();"
Time Zone Support
This feature demonstrates the ability to specify a time zone for the cron job. The code sample schedules a job to run at 11:30 AM, according to the 'America/New_York' time zone, from Monday to Friday.
"const CronJob = require('cron').CronJob;\nconst job = new CronJob('00 30 11 * * 1-5', function() {\n console.log('This runs at 11:30 AM (server time) every Monday through Friday.');\n}, null, true, 'America/New_York');\njob.start();"
Dynamic Job Scheduling
This feature allows for dynamic scheduling of jobs. The schedule can be updated or changed based on certain conditions or inputs. In the example, the 'dynamicSchedule' variable can be updated to change the job's schedule.
"const CronJob = require('cron').CronJob;\nlet dynamicSchedule = '00 30 11 * * 1-5'; // This can be dynamically changed\nconst job = new CronJob(dynamicSchedule, function() {\n console.log('This job's schedule can be dynamically changed.');\n}, null, true, 'America/Los_Angeles');\njob.start();"
node-schedule is a flexible cron-like and not-cron-like job scheduler for Node.js. It allows for more complex scheduling and includes features like job cancellation. It is a good alternative to cron when more flexibility is required.
Agenda is a job scheduling library for Node.js that uses MongoDB for job storage. It offers more robust job management features compared to cron, such as persistence, job prioritization, and repeating jobs. It's a good choice when jobs need to be managed across server restarts or in distributed systems.
Bull is a Redis-based queue system for Node.js. It is not a direct alternative to cron but can be used for scheduling through delayed jobs. It offers advanced features like job prioritization, concurrency control, and job events. Bull is suitable for applications requiring high reliability and real-time processing.
Cron is a tool that allows you to execute something on a schedule. This is typically done using the cron syntax. We allow you to:
child_process
npm install cron
As goes with semver, breaking backwards compatibility should be explicit in the versioning of your library. As such, we'll upgrade the version of this module in accordance with breaking changes (We're not always great about doing it this way so if you notice that there are breaking changes that haven't been bumped appropriately please let us know).
var CronJob = require('cron').CronJob;
var job = new CronJob(
'* * * * * *',
function() {
console.log('You will see this message every second');
},
null,
true,
'America/Los_Angeles'
);
// job.start() - See note below when to use this
Note - In the example above, the 4th parameter of CronJob()
automatically starts the job on initialization. If this parameter is falsy or not provided, the job needs to be explicitly started using job.start()
.
There are more examples available in this repository at: /examples
Asterisks e.g. *
Ranges e.g. 1-3,5
Steps e.g. */2
Read up on cron patterns here. Note the examples in the link have five fields, and 1 minute as the finest granularity, but this library has six fields, with 1 second as the finest granularity.
There are tools that help when constructing your cronjobs. You might find something like https://crontab.guru/ or https://cronjob.xyz/ helpful. But, note that these don't necessarily accept the exact same syntax as this library, for instance, it doesn't accept the seconds
field, so keep that in mind.
When specifying your cron values you'll need to make sure that your values fall within the ranges. For instance, some cron's use a 0-7 range for the day of week where both 0 and 7 represent Sunday. We do not. And that is an optimisation.
cron
!cron
and is planned to updated to match Unix cron
in v3.0.0 of node-cron
.Date
or Luxon DateTime
objects: Because computers take time to do things, there may be some delay in execution. This should be on the order of milliseconds. This module doesn't allow MS level granularity for the regular cron syntax, but does allow you to specify a real date of execution in either a javascript Date
object or a Luxon DateTime
object. When this happens you may find that you aren't able to execute a job that should run in the future like with new Date().setMilliseconds(new Date().getMilliseconds() + 1)
. This is due to those cycles of execution above. This wont be the same for everyone because of compute speed. When we tried it locally we saw that somewhere around the 4-5 ms mark was where we got consistent ticks using real dates, but anything less than that would result in an exception. This could be really confusing. We could restrict the granularity for all dates to seconds, but felt that it wasn't a huge problem so long as you were made aware. If this becomes more of an issue, We can revisit it.onTick
: Arrow functions get their this
context from their parent scope. Thus, if you use them, you will not get the this
context of the cronjob. You can read a little more in issue GH-47Parameter Based
job
- shortcut to new cron.CronJob()
.time
- shortcut to new cron.CronTime()
.sendAt
- tells you when a CronTime
will be run.timeout
- tells you when the next timeout is.CronJob
constructor(cronTime, onTick, onComplete, start, timeZone, context, runOnInit, utcOffset, unrefTimeout)
- Of note, the first parameter here can be a JSON object that has the below names and associated types (see examples above).
cronTime
- [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS Date object.onTick
- [REQUIRED] - The function to fire at the specified time. If an onComplete
callback was provided, onTick
will receive it as an argument. onTick
may call onComplete
when it has finished its work.onComplete
- [OPTIONAL] - A function that will fire when the job is stopped with job.stop()
, and may also be called by onTick
at the end of each run.start
- [OPTIONAL] - Specifies whether to start the job just before exiting the constructor. By default this is set to false. If left at default you will need to call job.start()
in order to start the job (assuming job
is the variable you set the cronjob to). This does not immediately fire your onTick
function, it just gives you more control over the behavior of your jobs.timeZone
- [OPTIONAL] - Specify the time zone for the execution. This will modify the actual time relative to your time zone. If the time zone is invalid, an error is thrown. By default (if this is omitted) the local time zone will be used. You can check the various time zones format accepted in the Luxon documentation. Note: This parameter supports minutes offsets, e.g. UTC+5:30
. Warning: Probably don't use both timeZone
and utcOffset
together or weird things may happen.context
- [OPTIONAL] - The context within which to execute the onTick method. This defaults to the cronjob itself allowing you to call this.stop()
. However, if you change this you'll have access to the functions and values within your context object.runOnInit
- [OPTIONAL] - This will immediately fire your onTick
function as soon as the requisite initialization has happened. This option is set to false
by default for backwards compatibility.utcOffset
- [OPTIONAL] - This allows you to specify the offset of your time zone rather than using the timeZone
param. This should be an integer representing the number of minutes offset (like 120
for +2 hours or -90
for -1.5 hours). Warning: Minutes offsets < 60 and >-60 will be treated as an offset in hours. This means a minute offset of 30
means an offset of +30 hours. Use the timeZone
param in this case. This behavior is planned to be removed in V3. Warning: Probably don't use both timeZone
and utcOffset
together or weird things may happen.unrefTimeout
- [OPTIONAL] - If you have code that keeps the event loop running and want to stop the node process when that finishes regardless of the state of your cronjob, you can do so making use of this parameter. This is off by default and cron will run as if it needs to control the event loop. For more information take a look at timers#timers_timeout_unref from the NodeJS docs.start
- Runs your job.stop
- Stops your job.setTime
- Stops and changes the time for the CronJob
. Param must be a CronTime
.lastDate
- Tells you the last execution date.nextDates
- Provides an array of the next set of dates that will trigger an onTick
.fireOnTick
- Allows you to override the onTick
calling behavior. This matters so only do this if you have a really good reason to do so.addCallback
- Allows you to add onTick
callbacks.CronTime
constructor(time)
time
- [REQUIRED] - The time to fire off your job. This can be in the form of cron syntax or a JS Date object.Join the Discord server! Here you can discuss issues and get help in a more casual forum than GitHub.
This project is looking for help! If you're interested in helping with the project please reach out to me (ncb000gt) on Twitter. We'd love for it to continue on, but it needs a lot of attention. You can also join the Discord server to learn more about what needs to be done.
Before submitting a bug, please search the existing issues, Discord conversations, and the web to see if someone else has run into the same issue before.
Because we can't magically know what you are doing to expose an issue, it is best if you provide a snippet of code. This snippet need not include your secret sauce, but it must replicate the issue you are describing. The issues that get closed without resolution tend to be the ones without code examples. Thanks.
This is a community effort project. In the truest sense, this project started as an open source project from cron.js and grew into something else. Other people have contributed code, time, and oversight to the project. At this point there are too many to name here so We'll just say thanks.
MIT
FAQs
Cron jobs for your node
The npm package cron receives a total of 1,596,997 weekly downloads. As such, cron popularity was classified as popular.
We found that cron demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.